const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()
exports.main = async (event, context) => {
	const wxContext = cloud.getWXContext()
	console.log(event)
	if (event._id) {
		var item = await db.collection('shop').doc(event._id).get()
		if (!item.data._openid || item.data._openid != wxContext.OPENID) {
			return {
				code: 20000,
				msg: '申请记录不存在'
			}
		}
	}
	let forms = {
		license_name: '营业执照名称',
		license_code: '统一社会信用代码',
		apply_name: '联系人姓名',
		apply_phone: '联系人电话',
		apply_wechat: '联系人微信',
		address: '地址',
		location: '坐标',
		license_image: '营业执照照片',
		cover_image: '门店照片'
	}
	for (var x in forms) {
		if (!event[x]) {
			return {
				code: 20001,
				msg: '请传入' + forms[x]
			}
		}
	}
	let shop = {
		license_name: event.license_name,
		license_code: event.license_code,
		apply_name: event.apply_name,
		apply_phone: event.apply_phone,
		apply_wechat: event.apply_wechat,
		address: event.address,
		location: event.location,
		license_image: event.license_image,
		cover_image: event.cover_image,
		status: 1,
		update_time: new Date()
	}
	if (event.subscribe) {
		shop.subscribe = true
	}
	if (item) {
		console.log(item.data)
		shop.examine = [{
			status: 1,
			time: shop.update_time
		}].concat(item.data.examine)
		await db.collection('shop').doc(item.data._id).update({
			data: shop
		})
		shop = await db.collection('shop').doc(item.data._id).get()
	} else {
		shop.create_time = shop.update_time
		shop.examine = [{
			status: 1,
			time: shop.create_time
		}]
		shop.name = shop.license_name
		shop.phone = shop.apply_phone
		shop.is_show = false
		shop.is_visit = false
		shop.content = ''
		shop._openid = wxContext.OPENID
		await db.collection('shop').add({
			data: shop
		}).then(res => {
			shop._id = res._id
			//增加staff
			let staff = {
				_openid: wxContext.OPENID,
				shop_id: res._id,
				group_id: 1,
				create_time: event.create_time,
				update_time: event.update_time
			}
			db.collection('staff').add({
				data: staff
			})
		})
		shop = await db.collection('shop').doc(shop._id).get()

	}

	return {
		code: 200,
		msg: '申请已提交',
		data: shop.data
	}

}